package com.conversationboard.controller;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.conversationboard.authenticator.AuthenticationCookie;
import com.conversationboard.model.User;

@WebServlet(name = "ChangePasswordControllerServlet", urlPatterns = "/ChangePasswordControllerServlet")
public class ChangePasswordControllerServlet extends HttpServlet {

	private static final long serialVersionUID = 3129347489785768794L;


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

		try {

			String userName = request.getUserPrincipal().getName();
			String password = request.getParameter("password");
			User user = User.get(userName);

			if (password != null && password.length() >= 6) {
				user.changePassword(password);
			} else {
				RequestDispatcher messageDispatcher = request.getRequestDispatcher("/Pages/messagepage.jsp");
				request.setAttribute("message", "Please choose a password at least six characters in length.");
				messageDispatcher.forward(request, response);
				return;
			}

			if (!SecurityChecks.passes(request, user, this)) {
				return;
			}

			AuthenticationCookie.removeCookies(request, response);

			RequestDispatcher dispatcher = request.getRequestDispatcher("/Pages/messagepage.jsp");
			request.setAttribute("message", "Your password has been successfully changed.");
			dispatcher.forward(request, response);

		} catch (SQLException e) {
			throw new ServletException(e);
		}

	}

}
